use crate::db::Db;
use rusqlite_from_row::FromRow;

#[derive(Debug, FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub address: Option<String>,
}

impl Db {
    /// 初始化用户表
    pub fn init_users(&self) {
        if !self.table_exists("users") {
            self.conn.execute(r#"
                create table users (
                    id integer primary key,
                    name text not null,
                    address text
                );
                "#, []).unwrap();
            println!("创建users表成功")
        }
    }
    /// 查询用户列表
    pub fn users(&self) -> Vec<User> {
        let mut stmt = self.conn.prepare("select * from users").unwrap();
        let result = stmt.query_map([], User::try_from_row).unwrap();
        let users: Vec<User> = result.into_iter().map(|r| r.unwrap()).collect();
        users
    }
}